#include "bookservice.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QUuid>

bookService::bookService()
{

}

QString bookService::addBook(QMap<QString, QString> params) {
    BookType* node = new BookType();
    node->SetId(params["id"].toInt());
    node->SetName(params["name"]);
    node->SetAuthor(params["author"]);
    node->SetCategory(params["cate"]);
    node->SetIntroduction(params["intro"]);

    this->bookRepository->AddNode(node);
    this->bookRepository->Save();

    QJsonObject obj;
    obj.insert("logid", QUuid::createUuid().toString());
    obj.insert("code", 200);
    obj.insert("message", "success");
    QJsonObject data;
    obj.insert("data", data);

    return QString(QJsonDocument(obj).toJson(QJsonDocument::Compact));
}

QString bookService::deleteBook(QMap<QString, QString> params) {
    BookType* node = new BookType();
    node->SetId(params["id"].toInt());

    this->bookRepository->DeleteNode(node->GetId());
    this->bookRepository->Save();

    QJsonObject obj;
    obj.insert("logid", QUuid::createUuid().toString());
    obj.insert("code", 200);
    obj.insert("message", "success");
    QJsonObject data;
    obj.insert("data", data);

    return QString(QJsonDocument(obj).toJson(QJsonDocument::Compact));
}

QString bookService::borrowBook(QMap<QString, QString> params) {
    UserBookType* node = new UserBookType();
    node->SetId(params["id"].toInt());
    node->SetBookId(params["bookId"].toInt());
    QDate date;
    date = date.currentDate().addDays(30);  //以借书日期为基础增加30天为默认的还书日期。

    node->SetYear(date.year());
    node->SetMonth(date.month());
    node->SetDay(date.day());
    this->userBookRepository->AddNode(node);
    this->userBookRepository->Save();

    QJsonObject obj;
    obj.insert("logid", QUuid::createUuid().toString());
    obj.insert("code", 200);
    obj.insert("message", "success");
    QJsonObject data;
    obj.insert("data", data);

    return QString(QJsonDocument(obj).toJson(QJsonDocument::Compact));
}

QString bookService::returnBook(QMap<QString, QString> params) {
    UserBookType* node = new UserBookType();
    // 删除一本书只要人的id和书的id，其他信息并不需要
    node->SetId(params["id"].toInt());
    node->SetBookId(params["bookId"].toInt());
    this->userBookRepository->DeleteNode(node->GetId());
    this->userBookRepository->Save();

    QJsonObject obj;
    obj.insert("logid", QUuid::createUuid().toString());
    obj.insert("code", 200);
    obj.insert("message", "success");
    QJsonObject data;
    obj.insert("data", data);

    return QString(QJsonDocument(obj).toJson(QJsonDocument::Compact));
}
